package com.ikangtai.shecare.personal;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.FormatUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;

public class ResetPasswordActivity extends BaseActivity implements View.OnClickListener {

    private TopBar topBar;
    private EditText key_edit, new_password_edit, re_new_password_edit;
    private String phoneNumber;
    private Button timeBtn;

    private static final int CHECK_KEY_OK = 1;
    private static final int CHECK_KEY_NOK = 2;
    private static final int CHECK_KEY_WRONG = 3;
    private static final int CHECK_KEY_OVERDUE = 4;
    private static final int RESETPASSWORD_OK = 5;
    private static final int RESETPASSWORD_NOK = 6;
    private static final int UNREGISTERED = 7;
    private static final int RESETPASSWORD_FORMAT_WRONG = 8;
    private static final int GET_KEY_OK = 9;
    private static final int GET_KEY_NOK = 10;

    private String keyCode;
    private String newPassword;
    private String reNewPassword;
    private TimeCount time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_personal_reset_password);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                Intent nextIntent = new Intent();
                nextIntent.setClass(getApplicationContext(), FindPasswordActivity.class);
                startActivity(nextIntent);
                finish();
            }

            @Override
            public void midLeftClick() {

            }

            @Override
            public void midRightClick() {

            }

            @Override
            public void rightClick() {

            }
        });
        key_edit = (EditText) findViewById(R.id.key_edit);
        new_password_edit = (EditText) findViewById(R.id.new_password_edit);
        re_new_password_edit = (EditText) findViewById(R.id.re_new_password_edit);
        timeBtn = (Button) findViewById(R.id.time_btn);
        timeBtn.setOnClickListener(this);
        findViewById(R.id.send_btn).setOnClickListener(this);

        Intent intent = getIntent();
        phoneNumber = intent.getStringExtra("phoneNumber");

        time = new TimeCount(60000, 1000);
        time.start();// 开始计时
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_btn:
                if (isValid()) {
                    resetPassword(keyCode);
                }
                break;
            case R.id.time_btn:
                sendByPhone(phoneNumber);
                time.start();// 开始计时
                break;
        }
    }

    /**
     * 检查文本框内容
     */
    private boolean isValid() {
        keyCode = key_edit.getText().toString().trim();
        newPassword = new_password_edit.getText().toString().trim();
        reNewPassword = re_new_password_edit.getText().toString().trim();

        if (0 == keyCode.length()) {
            Toast.makeText(getApplicationContext(), R.string.captcha_not_null, Toast.LENGTH_SHORT).show();
        } else if (0 == newPassword.length()) {
            Toast.makeText(getApplicationContext(), R.string.pass_not_null, Toast.LENGTH_SHORT).show();
        } else if (0 == reNewPassword.length()) {
            Toast.makeText(getApplicationContext(), R.string.pass_again_not_null, Toast.LENGTH_SHORT).show();
        } else if (!newPassword.equals(reNewPassword)) {
            Toast.makeText(getApplicationContext(), R.string.pass_not_conformity, Toast.LENGTH_SHORT).show();
        } else {
            return true;
        }
        return false;
    }

    /**
     * 检查验证码
     *
     * @param keyCode
     */
    private void resetPassword(String keyCode) {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "veri/verifyCode.json";
        try {
            okHttpClient.add("phoneNumber", phoneNumber);
            okHttpClient.add("code", keyCode);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            sendOKResp(CHECK_KEY_OK);
                            AppLog.i("check key code onResponse success!");
                        } else if (App.VERIFICATION_CODE_WRONG == respCode) {
                            sendReturnExceptionCode(CHECK_KEY_WRONG);
                            AppLog.i("check key code onResponse respCode failed! is:" + respCode);
                        } else if (App.VERIFICATION_CODE_OVERDUE == respCode) {
                            sendReturnExceptionCode(CHECK_KEY_OVERDUE);
                            AppLog.i("check key code onResponse respCode failed! is:" + respCode);
                        } else {
                            sendNOKResp(CHECK_KEY_NOK);
                            AppLog.i("check key code onResponse respCode failed! is:" + respCode);
                        }
                    } catch (JSONException e) {
                        AppLog.i("check key code onResponse failed!");
                        sendNOKResp(CHECK_KEY_NOK);
                        e.printStackTrace();
                    }
                }


            });
        } catch (JSONException e) {
            sendNOKResp(CHECK_KEY_NOK);
            e.printStackTrace();
        }
    }

    /**
     * post发送修改密码请求
     *
     * @param newPassword
     */
    private void sendNewPassword(final String newPassword) {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "login/resetPasswordByEmailOrPhone.json";
        try {
            okHttpClient.add("emailOrPhone", phoneNumber);
            okHttpClient.add("password", FormatUtil.md5(newPassword));
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            sendOKResp(RESETPASSWORD_OK);
                            AppLog.i("new password onResponse success!");
                        }else if(respCode == App.HTTP_RESP_TOKEN_TIME_OUT){
                            OKHttpUtil.setNewToken();
                            sendNewPassword(newPassword);
                        }else if (App.UNREGISTERED == respCode) {
                            sendReturnExceptionCode(UNREGISTERED);
                            AppLog.i("new password onResponse respCode failed! is:" + respCode);
                        } else if (App.FORMAT_WRONG == respCode) {
                            sendReturnExceptionCode(RESETPASSWORD_FORMAT_WRONG);
                            AppLog.i("new password onResponse respCode failed! is:" + respCode);
                        } else {
                            sendNOKResp(RESETPASSWORD_NOK);
                            AppLog.i("new password onResponse respCode failed! is:" + respCode);
                        }
                    } catch (JSONException e) {
                        AppLog.i("new password onResponse failed!");
                        sendNOKResp(RESETPASSWORD_NOK);
                        e.printStackTrace();
                    }
                }

                private void sendNOKResp(int returnCode) {
                    EventBus.getDefault().post(Integer.valueOf(returnCode));
                }

                private void sendOKResp(int returnCode) {
                    EventBus.getDefault().post(Integer.valueOf(returnCode));
                }

                private void sendReturnExceptionCode(int returnCode) {
                    EventBus.getDefault().post(Integer.valueOf(returnCode));
                }
            });
        } catch (JSONException e) {
            sendNOKResp(RESETPASSWORD_NOK);
            e.printStackTrace();
        }
    }

    private void sendNOKResp(int returnCode) {
        EventBus.getDefault().post(Integer.valueOf(returnCode));
    }

    private void sendOKResp(int returnCode) {
        EventBus.getDefault().post(Integer.valueOf(returnCode));
    }

    private void sendReturnExceptionCode(int returnCode) {
        EventBus.getDefault().post(Integer.valueOf(returnCode));
    }

    @Subcriber
    private void handleMyInfo(Integer returnCode){
        switch (returnCode){
            case CHECK_KEY_OK:
                sendNewPassword(newPassword);
                Toast.makeText(getApplicationContext(), R.string.captcha_success, Toast.LENGTH_SHORT).show();
                break;
            case CHECK_KEY_NOK:
                Toast.makeText(getApplicationContext(), R.string.captcha_faill, Toast.LENGTH_SHORT).show();
                break;
            case CHECK_KEY_WRONG:
                Toast.makeText(getApplicationContext(), R.string.captcha_not_sure, Toast.LENGTH_SHORT).show();
                break;
            case CHECK_KEY_OVERDUE:
                Toast.makeText(getApplicationContext(), R.string.captcha_out, Toast.LENGTH_SHORT).show();
                break;
            case RESETPASSWORD_OK:
                Toast.makeText(getApplicationContext(), R.string.new_pass_success, Toast.LENGTH_SHORT).show();
                finish();
                break;
            case RESETPASSWORD_NOK:
                Toast.makeText(getApplicationContext(), R.string.new_pass_fail, Toast.LENGTH_SHORT).show();
                break;
            case UNREGISTERED:
                Toast.makeText(getApplicationContext(), R.string.user_not_exist, Toast.LENGTH_SHORT).show();
                break;
            case RESETPASSWORD_FORMAT_WRONG:
                Toast.makeText(getApplicationContext(), R.string.character_string_format, Toast.LENGTH_SHORT).show();
                break;
            case GET_KEY_OK:
                Toast.makeText(getApplicationContext(), R.string.captcha_post_success, Toast.LENGTH_SHORT).show();
                break;
            case GET_KEY_NOK:
                Toast.makeText(getApplicationContext(), R.string.captcha_post_fail, Toast.LENGTH_SHORT).show();
                break;
        }
    }

    /**
     * 验证码定时器
     */
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            timeBtn.setText(R.string.get_captcha);
            timeBtn.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            timeBtn.setClickable(false);//防止重复点击
            timeBtn.setText(millisUntilFinished / 1000 + getString(R.string.again_get)
            );
        }
    }

    /**
     * 手机号修改密码，发送验证码
     *
     * @param userPhone
     */
    private void sendByPhone(final String userPhone) {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "veri/getCode.json";
        try {
            okHttpClient.add("phoneNumber", userPhone);
            okHttpClient.add("type", 2);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    sendNOKResp(GET_KEY_NOK);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            sendOKResp(GET_KEY_OK);
                            AppLog.i("find password by phone onResponse success!");
                        } else if (App.HTTP_RESP_TOKEN_TIME_OUT == respCode) {
                            sendReturnExceptionCode(UNREGISTERED);
                            AppLog.i("find password by phone onResponse respCode failed! is:" + respCode);
                        } else {
                            sendNOKResp(GET_KEY_NOK);
                            AppLog.i("find password by phone onResponse respCode failed! is:" + respCode);
                        }
                    } catch (JSONException e) {
                        AppLog.i("find password by phone onResponse failed!");
                        sendNOKResp(GET_KEY_NOK);
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            sendNOKResp(GET_KEY_NOK);
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

}
